'use strict';

const Controller = require('egg').Controller;

class UserController extends Controller {
  // 通过小程序获取当前用户信息
  async infoFromWeapp() {
    const { ctx, app } = this;
    const loginService = app.weapp.LoginService.create(ctx.request, ctx.response);
    const { userInfo } = await loginService.check();
    console.log('UserController userInfoFromWeapp userInfo', userInfo);
    const { openId } = userInfo;
    const user = await this.ctx.model.User.findOne({
      include: [{
        model: this.ctx.model.WechatAccount,
        where: { openId },
      }],
    });
    const opt = {};
    opt.include = [
      {
        as: 'users',
        model: ctx.model.User,
        where: { id: user.id },
      },
    ];
    const allFollowed = await this.ctx.model.Store.findAll(opt);// 查找所有已关注店铺
    const phone = await this.ctx.model.Phone.findOne({ where: { userId: user.id } });
    if (phone) {
      user.dataValues.phone = phone.number;
    }
    const alipay = await this.ctx.model.Alipay.findOne({ where: { userId: user.id } });
    if (alipay) {
      user.dataValues.alipayName = alipay.name;
      user.dataValues.alipayAccount = alipay.account;
    }
    console.log(' weapp infoFromWeapp allFollowed', allFollowed);
    console.log('weapp infoFromWeapp userInfo', user);
    ctx.body = {
      userInfo,
      user,
      allFollowed: allFollowed.length,
      bound: !!user,
    };
  }
  async loginFromWeapp() {
    const { ctx, app } = this;
    const loginService = app.weapp.LoginService.create(ctx.request, ctx.response);
    const data = await loginService.login();
    const { openId, nickName: nickname, avatarUrl } = data.userInfo;
    const [ wechatAccount ] = await this.ctx.model.WechatAccount.findOrCreate({
      defaults: { openId, avatarUrl },
      where: { openId },
    });
    await wechatAccount.update({ avatarUrl });
    console.log('loginFromWeapp wechatAccount.userId', wechatAccount.userId);
    if (wechatAccount && !wechatAccount.userId) {
      console.log('wechatAccount && !wechatAccount.userId');
      const defaults = { nickname, role: 'general' };
      console.log('wechatAccount && !wechatAccount.userId defaults', defaults);
      const user = await this.ctx.model.User.create(defaults);
      console.log('wechatAccount && !wechatAccount.userId user', user);
      await wechatAccount.update({ userId: user.id });
    }
    ctx.body = data;
  }
  // 绑定邀请者
  async bindInviterFromWeapp() {
    console.log('bindInviterFromWeappbindInviterFromWeapp');
    const { ctx } = this;
    const { inviterId } = ctx.request.query;
    console.log('bindInviterFromWeapp inviterId', inviterId);
    if (inviterId) {
      const loginService = ctx.app.weapp.LoginService.create(ctx.request, ctx.response);
      const checkedData = await loginService.check();
      const { openId } = checkedData.userInfo;
      const wechatAccount = await this.ctx.model.WechatAccount.findByPk(openId);
      console.log('bindInviterFromWeapp wechatAccount', wechatAccount);
      const user = await this.ctx.model.User.findByPk(wechatAccount.userId); // 找到当前用户信息
      console.log('bindInviterFromWeapp user', user);
      const inviterUser = await this.ctx.model.User.findByPk(inviterId);// 找到邀请者用户信息
      console.log('bindInviterFromWeapp inviterUser', inviterUser);
      const opt = {
        where: {
          id: user.id,
        },
      };
      const current = await this.ctx.model.User.findOne(opt);
      console.log('bindInviterFromWeapp current', current);
      // 判断当前用户是否为1分钟内创建
      if (!user.inviterId && inviterUser && current) {
        await user.update({ inviterId });
        const inviterPhone = await this.ctx.model.Phone.findOne({
          where: {
            userId: inviterUser.id,
          },
        });
        // 会员锁粉
        const sendData = {
          phone: inviterPhone.number,
          nickname: user.nickname,
          TemplateCode: 'SMS_158492778',
        };
        console.log('会员锁粉 bindInviterFromWeapp sendData', sendData);
        await this.ctx.service.smsCode.send(sendData);
        ctx.status = 204;
      } else {
        ctx.status = 204;
      }
    } else {
      ctx.status = 204;
    }
  }
  // 收藏功能
  async follow() {
    console.log('follow');
    const { ctx, app } = this;
    const { storeId, status } = ctx.request.query;
    const store = await ctx.model.Store.findById(storeId);
    console.log('await this.ctx.model.Store.findById store', store);
    if (store) {
      const loginService = app.weapp.LoginService.create(ctx.request, ctx.response);
      const { userInfo } = await loginService.check();
      const { openId } = userInfo;
      const weappUser = await this.ctx.model.WechatAccount.findByPk(openId);
      const { userId } = weappUser;
      const user = await ctx.model.User.findByPk(userId);
      if (!status) {
        await store.addUser(user);
        this.ctx.status = 204;
      } else {
        await store.removeUser(user);
        this.ctx.status = 204;
      }
    } else {
      this.ctx.status = 403;
    }
  }
  // 绑定手机号
  async bindPhoneBySmsCode() {
    this.ctx.validate({
      phone: 'string',
      code: 'string',
    });
    const { phone, code } = this.ctx.request.body;
    if (await this.ctx.model.SmsCode.verify(phone, code)) {
      const { ctx, app } = this;
      const loginService = app.weapp.LoginService.create(ctx.request, ctx.response);
      const data = await loginService.check();
      console.log('UserController bindPhoneBySmsCode data', data);
      const { openId } = data.userInfo;
      const wechatAccount = await this.ctx.model.WechatAccount.findByPk(openId);
      const phoneUser = await this.ctx.model.Phone.findOne({
        where: {
          userId: wechatAccount.userId,
        },
      });
      if (phoneUser) {
        const data = { number: phone };
        await phoneUser.update(data);
        ctx.body = phoneUser;
        this.ctx.status = 204;
      } else {
        const newPhoneUser = await this.ctx.model.Phone.create({
          number: phone,
          userId: wechatAccount.userId,
        });
        ctx.body = newPhoneUser;
        this.ctx.status = 204;
      }
    } else {
      this.ctx.message = '验证码错误';
      this.ctx.status = 403;
    }
  }
  // 绑定支付宝账号
  async bindAlipayByUser() {
    this.ctx.validate({
      name: 'string',
      account: 'string',
    });
    const { name, account } = this.ctx.request.body;
    if (name && account) {
      const { ctx, app } = this;
      const loginService = app.weapp.LoginService.create(ctx.request, ctx.response);
      const data = await loginService.check();
      console.log('UserController bindPhoneBySmsCode data', data);
      const { openId } = data.userInfo;
      // 找到当前微信用户
      const wechatAccount = await this.ctx.model.WechatAccount.findByPk(openId);
      const alipayUser = await this.ctx.model.Alipay.findOne({
        where: {
          userId: wechatAccount.userId,
        },
      });
      console.log('alipayUseralipayUseralipayUseralipayUser', alipayUser);
      if (alipayUser) {
        const data = { name, account };
        await alipayUser.update(data);
        this.ctx.body = alipayUser;
        this.ctx.status = 204;
      } else {
        // 创建支付宝账户
        const newAlipayUser = await this.ctx.model.Alipay.create({
          name,
          account,
          userId: wechatAccount.userId,
        });
        this.ctx.body = newAlipayUser;
        this.ctx.status = 204;
      }


    } else {
      this.ctx.message = '参数不完整';
      this.ctx.status = 403;
    }
  }
  // 请求发送验证码 trove
  async smsCode() {
    this.ctx.validate({ phone: 'string' });
    await this.ctx.model.SmsCode.send(this.ctx.request.body.phone);
    this.ctx.status = 204;
  }
  // 用户信息记录
  async record() {
    const { ctx, app } = this;
    this.ctx.validate({
      name: { type: 'string', required: false },
      nickname: { type: 'string', required: false },
      imageHash: { type: 'string', required: false },
      receiverAddress: { type: 'string', required: false },
      receiverName: { type: 'string', required: false },
      receiverPhone: { type: 'string', required: false },
    });
    const loginService = app.weapp.LoginService.create(ctx.request, ctx.response);
    const { userInfo } = await loginService.check();
    console.log('UserController userInfoFromWeapp userInfo', userInfo);
    const { openId } = userInfo;
    const wxUser = await ctx.model.WechatAccount.findByPk(openId);
    const user = await ctx.model.User.findByPk(wxUser.userId);
    const { name, nickname, imageHash, receiverAddress, receiverName, receiverPhone } = this.ctx.request.body;
    const data = {};
    if (name) data.name = name;
    if (nickname) data.nickname = nickname;
    if (receiverAddress) data.receiverAddress = receiverAddress;
    if (receiverName) data.receiverName = receiverName;
    if (receiverPhone) data.receiverPhone = receiverPhone;
    if (imageHash) {
      await this.ctx.service.file.record('image', imageHash);
      data.fileHash = imageHash;
    }
    await user.update(data);
    this.ctx.status = 204;
  }
}

module.exports = UserController;
